package com.yqh.wechat.controller;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yqh.wechat.common.AppResponse;
import com.yqh.wechat.util.WechatUtil;
import com.yqh.wechat.util.XMLUtil;

/**
 * 现金红包
 * @author Yang.Qinghui
 * 接口文档：https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
 */
@RestController
@RequestMapping("/cash")
public class WechatCashController {
	
	private static final String APPID = "";
	private static final String MID = "";
	private static final String API_KEY = "";
	
	private static final String P12_PATH = "";	// 证书地址
	private static final String CASH_SEND_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
	
	@RequestMapping("/send")
	public AppResponse send() throws Exception{
		
		AppResponse resp = new AppResponse();
		
		String send_name = "";
		String re_openid = "";
		Integer total_amount = 100;
		Integer total_num = 1;
		String wishing = "";
		String act_name = "";
		String remark = "";
		
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		
		parameters.put("nonce_str", WechatUtil.getRandomStringByLength(12));
		parameters.put("mch_billno", WechatUtil.getCurrTime());
		parameters.put("mch_id", MID);
		parameters.put("wxappid", APPID);
		parameters.put("send_name", send_name);
		parameters.put("re_openid", re_openid);
		parameters.put("total_amount", total_amount);
		parameters.put("total_num", total_num);
		parameters.put("wishing", wishing);
		parameters.put("client_ip", WechatUtil.localIp());
		parameters.put("act_name", act_name);
		parameters.put("remark", remark);
		parameters.put("sign", WechatUtil.createSign("UTF-8", parameters, API_KEY));
		
		String requestXml = WechatUtil.getRequestXml(parameters);
		
		String strxml = doSSLPost(CASH_SEND_URL, requestXml);
		
		Map<String, String> resultMap = XMLUtil.doXMLParse(strxml);
		
		
		
		
		return resp;
		
	}
	

	// 证书请求
	public static String doSSLPost(String url, String data) throws Exception{
		
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		FileInputStream instream = new FileInputStream(P12_PATH);
		try {
			keyStore.load(instream, MID.toCharArray());	//该密码的值为微信商户号（mch_id）
		} finally {
			instream.close();
		}
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, MID.toCharArray())	//该密码的值为微信商户号（mch_id）
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
			
		try {
			HttpPost httpPost = new HttpPost(CASH_SEND_URL);	// 设置响应头信息
//			httpPost.addHeader("Connection", "keep-alive");
//			httpPost.addHeader("Accept", "*/*");
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//			httpPost.addHeader("Host", "api.mch.weixin.qq.com");
//			httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
//			httpPost.addHeader("Cache-Control", "max-age=0");
//			httpPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
			httpPost.setEntity(new StringEntity(data, "UTF-8"));
			CloseableHttpResponse response = httpClient.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				String	result = EntityUtils.toString(entity, "UTF-8");
				EntityUtils.consume(entity);
				return result;
			} finally {
				response.close();
			}
		} finally {
			httpClient.close();
		}
	}
	

}
